﻿package kit4j.tests.jdk.console;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestRuntime {
	
	private static Process pro;
	
	private static ExecutorService exe;

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		initPro();
		startInput();
		startOutput();
	}
	
	private static void initPro() throws IOException {
		pro = Runtime.getRuntime().exec("cmd");
	}
	
	private static void startInput() {
		final Scanner sc = new Scanner(System.in);
		final PrintWriter out = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(pro.getOutputStream())), true);

		getExecutor().submit(new Runnable() {
			public void run() {
				String input;
				while(sc.hasNext()) {
					input = sc.next();
					if("exit".equals(input)) {
						System.exit(0);
					}
					out.println(sc.next());
				}
			}
		});
	}
	
	private static void startOutput() {
		final BufferedReader in = new BufferedReader(new InputStreamReader(
				pro.getInputStream()));
		
		getExecutor().submit(new Runnable() {
			public void run() {
				while(true) {
					try {
						System.out.println(in.readLine());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	private static ExecutorService getExecutor() {
		if(exe == null) {
			exe = Executors.newCachedThreadPool();
		}
		
		return exe;
	}
}
